package com.example.webweatherapp

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.webweatherapp.weather.Forecast
import com.example.webweatherapp.weather.weather
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class MainActivity2 : AppCompatActivity() {
    val baseURL = "http://t.weather.itboy.net/api/weather/city/"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)

        val cityCode = intent.getStringExtra("city_code")
        val queue = Volley.newRequestQueue(this)
        val stringRequest = StringRequest(baseURL + cityCode,
            {
                val gson = Gson()
                val WeatherType = object : TypeToken<weather>() {}.type
                val weather = gson.fromJson<weather>(it, WeatherType)
                val city = findViewById<android.widget.TextView>(R.id.textView_city)
                city.text = weather.cityInfo.city
                val province = findViewById<android.widget.TextView>(R.id.textView_province)
                province.text = weather.cityInfo.parent
                val shidu = findViewById<android.widget.TextView>(R.id.textView_shidu)
                shidu.text = weather.data.shidu
                val wendu = findViewById<android.widget.TextView>(R.id.textView_wendu)
                wendu.text = weather.data.wendu

                val firstDay = weather.data.forecast.first()
                val img = findViewById<android.widget.ImageView>(R.id.imageView)
                when(firstDay.type){
                    "晴" -> img.setImageResource(R.drawable.sun)
                    "阴" -> img.setImageResource(R.drawable.cloud)
                    "多云" -> img.setImageResource(R.drawable.mcloud)
                    "小雨" -> img.setImageResource(R.drawable.rain)
                    "雪" -> img.setImageResource(R.drawable.snow)
                    else -> img.setImageResource(R.drawable.thunder)
                }
                val adapter = ArrayAdapter<Forecast>(this, android.R.layout.simple_list_item_1, weather.data.forecast)
                val listView = findViewById<ListView>(R.id.listView)
                listView.adapter = adapter

                Log.d("MainActivity2", "${weather.cityInfo.city} ${weather.cityInfo.parent}")
            },
            {
                Log.d("MainActivity2","$it" )
            })
        queue.add(stringRequest)
    }
}